/**当前登录客户ip */
import { defineStore } from 'pinia'
interface IBaseUrl {
  EnjoyMain?: string;
  EnjoyCRM?: string;
  EnjoyMall?: string;
  EnjoyMallSCM?: string;
  EnjoyMPM?: string;
  EnjoyOA?: string;
  EnjoyRMIS?: string;
}

interface State {
  EnjoyMain: string;
  EnjoyCRM: string;
  EnjoyMall: string;
  EnjoyOA: string;
  EnjoyRMIS: string;
  customer?: ICustomer | undefined | null;
  token?: string;
  EnjoyBaseURL?: IBaseUrl;
  ImageBaseUrl?: string;
}


interface ICustomerApplication {
  c_cloud_id: string;
  c_application: string;
  c_ismain_app: string;
  c_name: string;
  c_status: string;
  c_modified_user: string;
  c_modified_dt: any;
  c_note: string;
  c_mobile_service_ip: string;
  c_request_http_type: string;
  c_is_hiddenid: string;
}

interface ICustomer {
  EnjoyMain?: ICustomerApplication;
  ID?: string;
  EnjoyCRM?: ICustomerApplication;
  EnjoyMall?: ICustomerApplication;
  EnjoyMallSCM?: ICustomerApplication;
  EnjoyMPM?: ICustomerApplication;
  EnjoyOA?: ICustomerApplication;
  EnjoyRMIS?: ICustomerApplication;
}

export const useLoginStore = defineStore('LoginStore', {
  state: (): State => ({
    EnjoyMain: '',
    EnjoyCRM: '',
    EnjoyMall: '',
    EnjoyOA: '',
    EnjoyRMIS: '',
    token: '',
    customer: undefined, // TODO 待修改持久化
    EnjoyBaseURL: {
      EnjoyMain: '',
      EnjoyCRM: '',
      EnjoyMall: '',
      EnjoyMallSCM: '',
      EnjoyMPM: '',
      EnjoyOA: '',
      EnjoyRMIS: '',
    },
    ImageBaseUrl: "",
  }),
  actions: {
    updateEnjoyIp(val: {[key: string]: string}) {
      this.EnjoyMain = val.EnjoyMain || '';
      this.EnjoyCRM = val.EnjoyCRM || '';
      this.EnjoyMall = val.EnjoyMall || '';
      this.EnjoyOA = val.EnjoyOA || '';
      this.EnjoyRMIS = val.EnjoyRMIS || '';
      if (val.EnjoyMain) {
        this.updateImageBaseUrl();
      }
    },
    setCustomer(value: ICustomer) {
      this.customer = value;
      this.setBaseUrl(value);
    },
    setToken(value: string) {
      this.token = value;
    },
    setBaseUrl(customer: ICustomer) {
      const baseURL = {};
      Object.keys(customer).forEach(key => {
        if (key.startsWith('Enjoy')) {
          if (customer[key].c_request_http_type && customer[key].c_mobile_service_ip) {
            baseURL[key] = customer[key].c_request_http_type + '://' + customer[key].c_mobile_service_ip;
          }
        }
      })
      this.EnjoyBaseURL = baseURL;
    },
    updateImageBaseUrl() {
      if (this.EnjoyMain) {
        const match = this.EnjoyMain.match(/http:\/\/.*?\/mbmv5/);
        this.ImageBaseUrl = match ? match[0] : "";
      } else {
        this.ImageBaseUrl = "";
      }
    }
  },
})
